<template>
    <!-- 结算中心/结算账单 -->
    <div class="settlementBill">
        <div class="top_operation">
            <div class="every_operation" v-if="isRegionShow">
                <span><b style="color:red;">*</b> 大区：</span>
                <a-select
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="regionChange" 
                    v-model="regionId" 
                    placeholder="请选择大区"
                >
                    <a-select-option :key="index" v-for="(item, index) in regionList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isCityShow">
                <span><b style="color:red;">*</b> 城市：</span>
                <a-select 
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="cityChange" 
                    v-model="cityId"
                    placeholder="请选择城市"
                >
                    <a-select-option :key="index" v-for="(item, index) in cityList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isWareShow">
                <span><b style="color:red;">*</b> 仓库：</span>
                <a-select
                    show-search
                    :filter-option="filterOption" 
                    style="width: 195px" 
                    @change="warehouseChange" 
                    v-model="organizeId"
                    placeholder="请选择仓库"
                >
                    <a-select-option :key="index" v-for="(item, index) in warehouseList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            
            <div class="every_operation">
                <span>客户：</span>
                <a-select style="width: 195px"
                    show-search
                    :filter-option="filterOption"
                    @change="customerChange" 
                    v-model="customerCode" 
                    placeholder="请选择客户"
                    allowClear
                >
                    <a-select-option :key="index" v-for="(item, index) in customerList" :value="item.customerCode">
                        {{item.customerName}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>货主：</span>
                <a-select style="width: 195px" 
                    show-search
                    :filter-option="filterOption"
                    @change="handleChange" 
                    v-model="ownerCode"
                    placeholder="请选择货主"
                    allowClear
                >
                    <a-select-option :key="index" v-for="(item, index) in ownerList" :value="item.ownerCode">
                        {{item.ownerName}}
                    </a-select-option>
                </a-select>
            </div>

            <div class="every_operation">
                <span>触发时间：</span>
                <a-range-picker
                    v-model="triggerTime"
                    :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')] }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['Start Date', 'End Date']"
                    @change="triggerTimeChange"
                    @ok="triggerTimeOk"
                    style="width:195px;"
                />
            </div>

            <div class="every_operation">
                <span>账单类型：</span>
                <a-select style="width: 195px" 
                    show-search
                    :filter-option="filterOption"
                    @change="handleChange" 
                    v-model="billType"
                    placeholder="请选择账单类型"
                    allowClear
                >
                    <a-select-option value="CTOP">
                        客户支付结算账单
                    </a-select-option>
                    <a-select-option value="CTOE">
                        支付快递结算账单
                    </a-select-option>
                </a-select>
            </div>

            <div class="button_div" style="margin-top:10px;">
                <a-button type="primary" icon="search" @click="onSearch()">搜索</a-button>
                <!-- <a-button type="primary" icon="sync" style="margin-left:20px;" @click="onReset()">重置</a-button> -->
            </div>
        </div>

        <div class="table_div">
            <!-- <a-button type="primary" @click="addBill()">手动账单</a-button> -->
            <a-dropdown>
                <a-menu slot="overlay" @click="handleMenuClick">
                    <a-menu-item key="CTOP">
                        客户支付结算账单
                    </a-menu-item>
                    <a-menu-item key="CTOE">
                        支付快递结算账单
                    </a-menu-item>
                </a-menu>
                <a-button type="primary"> 手动账单 <a-icon type="down" /> </a-button>
            </a-dropdown>

            <div class="table_div_main">
                <a-table
                    :loading="tableLoading"
                    :columns="columns" 
                    :data-source="data"
                    :pagination="false"
                    bordered
                    rowKey="id"
                >
                    <span slot="billTime" href="javascript:;" slot-scope="text, record">
                        <a-tooltip placement="bottom">
                            <template slot="title">
                                <span>{{record.billTimeBegin}} 至 {{record.billTimeEnd}}</span>
                            </template>
                            <span>{{record.billTimeBegin}} 至 {{record.billTimeEnd}}</span>
                        </a-tooltip>
                    </span>
                    <span slot="timeConsuming" href="javascript:;" slot-scope="text, record">
                        <span>{{record.timeConsuming}}分钟</span>
                    </span>
                    <span slot="status" href="javascript:;" slot-scope="text, record">
                        <span v-if="record.status == 'doing'">生成中</span>
                        <span v-else-if="record.status == 'done'">生成完成</span>
                        <span v-else>生成失败</span>
                    </span>
                    <span slot="billType" href="javascript:;" slot-scope="text, record">
                        <span v-if="record.billType == 'CTOP'">客户支付结算账单</span>
                        <span v-else>支付快递结算账单</span>
                    </span>
                    <a slot="fileName" href="javascript:;" slot-scope="text, record">
                        <a-tooltip placement="bottom">
                            <template slot="title">
                                <span>{{text}}</span>
                            </template>
                            <span @click="exportHand(record)">{{text}}</span>
                        </a-tooltip>
                    </a>
                </a-table>
                <!-- 底部分页组件 -->
                <BottomPagination
                    :total="total"
                    @pageChange="pageChange"
                    @sizeChange="sizeChange"
                ></BottomPagination>
            </div>
            <!-- 操作费右滑抽屉 -->
            <a-drawer
                :title="drawerTitle"
                :placement="placement"
                :closable="false"
                :visible="visible"
                @close="onClose"
                width="500"
            >
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
                    labelAlign="left"
                >

                    <a-form-model-item label="客户" prop="customerCode">
                        <a-select
                            show-search
                            :filter-option="filterOption" 
                            style="width: 100%;" 
                            @change="formCustomerChange" 
                            v-model="form.customerCode"
                            placeholder="请选择客户"
                        >
                            <a-select-option :key="index" v-for="(item, index) in form.customerList" :value="item.customerCode">
                                {{item.customerName}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>

                    <a-form-model-item label="货主">
                        <a-select
                            show-search
                            :filter-option="filterOption" 
                            style="width: 100%;" 
                            @change="formOwnerChange" 
                            v-model="form.ownerCode"
                            placeholder="请选择货主"
                            allowClear
                        >
                            <a-select-option :key="index" v-for="(item, index) in form.ownerList" :value="item.ownerCode">
                                {{item.ownerName}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>

                    <a-form-model-item label="账单日期" prop="billTime">
                        <a-range-picker
                            v-model="form.billTime"
                            :disabled-date="disabledDate"
                            :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('00:00:00', 'HH:mm:ss')] }"
                            @clearChange="clearChange"
                            @calendarChange="onCalendarChange"
                            @openChange="openChange"
                            format="YYYY-MM-DD HH:mm:ss"
                            @change="billTimeChange"
                            style="maxWidth:100%;"
                            @ok="billTimeOk"
                        />
                    </a-form-model-item>

                    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
                        <a-button type="primary" @click="onSubmit">
                            开始生成
                        </a-button>
                        <a-button style="width:88px;margin-left:10px;" @click="cancelForm">
                            取消
                        </a-button>
                    </a-form-model-item>
                </a-form-model>
            </a-drawer>
        </div>
    </div>
</template>

<script>
    const columns = [
        {
            title: '客户',
            dataIndex: 'customerCode',
            key: 'customerCode',
            align: 'center',
            width: '80px',
            ellipsis: true,
        },
        {
            title: '货主',
            dataIndex: 'ownerCode',
            key: 'ownerCode',
            align: 'center',
            width: '80px',
            ellipsis: true,
        },
        {
            title: '结算账期',
            dataIndex: 'billTime',
            key: 'billTime',
            align: 'center',
            width: '310px',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'billTime' 
            },
        },
        {
            title: '触发时间',
            dataIndex: 'triggerTime',
            key: 'triggerTime',
            align: 'center',
            width: '160px',
            ellipsis: true,
        },
        {
            title: '耗时',
            dataIndex: 'timeConsuming',
            key: 'timeConsuming',
            align: 'center',
            width: '80px',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'timeConsuming' 
            },
        },
        {
            title: '账单总金额(元)',
            dataIndex: 'billAmount',
            key: 'billAmount',
            align: 'center',
            width: '130px',
            ellipsis: true,
            customRender: (text, record, index) => {
                if(text == null){
                    return ''
                }else{
                    return Math.floor(text * 100) / 100;
                }
            }
        },
        {
            title: '生成方式',
            dataIndex: 'buildMode',
            key: 'buildMode',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            width: '100px',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'status' 
            },
        },
        {
            title: '账单类型',
            dataIndex: 'billType',
            key: 'billType',
            align: 'center',
            width: '145px',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'billType' 
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '附件(账单下载)',
            dataIndex: 'fileName',
            key: 'fileName',
            align: 'center',
            width: '300px',
            ellipsis: true,
            scopedSlots: { 
                customRender: 'fileName' 
            },
        },
    ];

    const key = 'downFile';

    import moment from 'moment'
    import BottomPagination from '../meter/BottomPagination'
    import { getHeadquarters, getRegion, getCity, getWarehouse, getBillList, manualSettlement, downloadBill, getCustomerName, getOwnerName, } from '@/api/api'
    import { downFile } from '@/api/manage'
    export default {
        name: "SettlementBill",
        components: {
            BottomPagination,
        },
        data () {
            return {
                code: '',
                headquartersId: '', // 总部id
                regionId: undefined, // 大区id
                cityId: undefined, // 城市id
                organizeId: undefined, // 仓库id
                regionList: [],
                cityList: [],
                warehouseList: [],
                customerCode: undefined,
                customerList: [],
                ownerCode: undefined,
                ownerList: [],
                isRegionShow: true,
                isCityShow: true,
                isWareShow: true,
                triggerTime: [], // 账单日期
                triggerTime_begin: '',
                triggerTime_end: '',
                billType: undefined,
                columns,
                data: [],
                tableLoading: false,
                visible: false,
                placement: 'right',
                drawerTitle: '手动账单',
                labelCol: { span: 7 },  
                wrapperCol: { span: 16 },
                form: {
                    code: '',
                    regionList: [],
                    cityList: [],
                    warehouseList: [],
                    regionId: '', // 大区id
                    cityId: '', // 城市id
                    organizeId: '', // 仓库id
                    customerCode: '',
                    customerList: [],
                    ownerCode: '',
                    ownerList: [],
                    billTime: [], // 账单日期
                    billTimeBegin: '',
                    billTimeEnd: '',
                },
                rules: {
                    // regionId: [
                    //     { required: true, message: '请选择大区', trigger: 'change' },
                    // ],
                    // cityId: [
                    //     { required: true, message: '请选择城市', trigger: 'change' },
                    // ],
                    // organizeId: [
                    //     { required: true, message: '请选择仓库', trigger: 'change' },
                    // ],
                    customerCode: [
                        { required: true, message: '请选择客户', trigger: 'change' },
                    ],
                    ownerCode: [
                        { required: true, message: '请选择货主', trigger: 'change' },
                    ],
                    billTime: [
                        { required: true, message: '请选择账单日期', trigger: 'change' },
                    ],
                },
                validStatus: true,
                pageNo: 1,
                pageSize: 10,
                total: 0,
            }
        },
        created() {
            this.getHeadquartersList()
        },
        methods: {
            moment,
            // 选择框过滤
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            // 选择器
            handleChange(value) {
                console.log(`selected ${value}`);
            },
            // 获取总部
            getHeadquartersList(){
                let params = {}
                getHeadquarters(params).then((res)=>{
                    if(res.success){
                        this.headquartersId = res.result.organizeOrgList[0].id
                        this.getRegionList()
                    }
                })
            },
            // 获取大区
            getRegionList(){
                let params = {id: this.headquartersId}
                getRegion(params).then((res)=>{
                    if(res.success){
                        this.regionList = res.result.organizeOrgList
                        if(this.regionList.length === 1){
                            this.regionId = this.regionList[0].id
                            this.getCityList()
                        }
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 选择大区
            regionChange(value){
                this.regionId = value 
                this.cityId = undefined
                this.organizeId = undefined
                this.cityList = []
                this.warehouseList = []
                this.getCityList()
                this.customerCode = undefined
                this.customerList = []
                this.ownerCode = undefined
                this.ownerList = []
            },
            // 获取城市
            getCityList(){
                let params = {
                    areaIds: this.regionId
                }
                getCity(params).then((res)=>{
                    if(res.success){
                        this.cityList = res.result.organizeOrgList
                        if(this.cityList.length === 1){
                            this.cityId = this.cityList[0].id
                            this.getWarehouseList()
                        }
                    }
                })
            },
            // 选择城市
            cityChange(value){
                this.cityId = value
                this.organizeId = undefined
                this.warehouseList = []
                this.getWarehouseList()
                this.customerCode = undefined
                this.customerList = []
                this.ownerCode = undefined
                this.ownerList = []
            },
            // 获取仓库
            getWarehouseList(){
                let params = {
                    cityIds: this.cityId
                }
                getWarehouse(params).then((res)=>{
                    if(res.success){
                        this.warehouseList = res.result.organizeOrgList
                        if(this.warehouseList.length === 1){
                            this.organizeId = this.warehouseList[0].id
                            this.code = this.warehouseList[0].code
                            this.form.code = this.warehouseList[0].code
                            this.getCustomerName()
                        }
                    }
                })
            },
            // 选择仓库
            warehouseChange(value){
                this.organizeId = value
                
                for(var item of this.warehouseList){
                    if(item.id == this.organizeId){
                        this.form.code = item.code
                    }
                }
                for(var item of this.warehouseList) {
                    if(item.id === this.organizeId) {
                        this.code = item.code
                        this.customerCode = undefined
                        this.customerList = []
                        this.ownerCode = undefined
                        this.ownerList = []
                        this.form.customerCode = undefined
                        this.form.customerList = []
                        this.getCustomerName()
                    }
                }
            },
            // 获取客户名称列表
            getCustomerName() {
                let params = {
                    whCode: this.code,
                }
                getCustomerName(params).then((res)=>{
                    if(res.success){
                        this.customerList = res.result
                        this.form.customerList = res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 选择客户
            customerChange() {
                this.ownerCode = undefined
                if(this.customerCode) {
                    this.getOwnerName()
                }
            },
            // 获取货主名称列表
            getOwnerName() {
                let params = {
                    whCode: this.code,
                    customerCode: this.customerCode,
                }
                getOwnerName(params).then((res)=>{
                    if(res.success){
                        this.ownerList = res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },

            // 账单日期
            triggerTimeChange(value, dateString) {
                this.triggerTime = value
                this.triggerTime_begin = dateString[0]
                this.triggerTime_end = dateString[1]
                console.log(value, dateString);
            },
            triggerTimeOk(value) {
                console.log('onOk: ', value);
            },
            onSearch() {
                if( (this.regionId == '' || this.regionId == undefined) || (this.cityId == '' || this.cityId == undefined) || (this.organizeId == '' || this.organizeId == undefined) ){
                    this.$message.warning('搜索前请选择大区、城市和仓库！')
                }else{
                    this.pageNo = 1
                    this.getBillList()
                }
            },
            getBillList() {
                let params = {
                    whCode: this.code,
                    customerCode: this.customerCode,
                    ownerCode: this.ownerCode,
                    triggerTime_begin: this.triggerTime_begin,
                    triggerTime_end: this.triggerTime_end,
                    billType: this.billType,
                    pageSize: this.pageSize,
                    pageNo: this.pageNo,
                    delFlag: 0,
                }
                this.tableLoading = true
                getBillList(params).then((res)=>{
                    this.tableLoading = false
                    if(res.success){
                        if(res.result && res.result.records){
                            this.data = res.result.records
                            this.total = res.result.total
                        }
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            },
            handleMenuClick(e) {
                this.form.billType = e.key
                if( (this.regionId == '' || this.regionId == undefined) || (this.cityId == '' || this.cityId == undefined) || (this.organizeId == '' || this.organizeId == undefined) ){
                    this.$message.warning('新增手动账单前请选择大区、城市和仓库！')
                }else{
                    this.addBill()
                }
            },
            // 手动账单
            addBill() {
                this.visible = true
                // 只有验证失败，新增的时候才重置验证状态
                if(this.validStatus === false) {
                    this.$refs.ruleForm.resetFields()
                }
                this.form.regionId = ''
                this.form.cityId = ''
                this.form.organizeId = ''
                this.form.customerCode = undefined
                // this.form.customerList = []
                this.form.ownerCode = undefined
                this.form.ownerList = []
                this.form.billTime = []
                this.form.cityList = []
                this.form.warehouseList = []

            },
            billTimeChange(value, dateString) {
                this.form.billTime = value
                this.form.billTimeBegin = dateString[0]
                this.form.billTimeEnd = dateString[1]
            },
            billTimeOk(value) {
                console.log('onOk: ', value);
            },
            onClose() {
                this.visible = false;
            },
            // 结算账单表单
            onSubmit() {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        this.validStatus = true
                        let params = {
                            whCode: this.form.code,
                            customerCode: this.form.customerCode,
                            ownerCode: this.form.ownerCode,
                            billTimeBegin: this.form.billTimeBegin,
                            billTimeEnd: this.form.billTimeEnd,
                            billType: this.form.billType,
                        }
                        manualSettlement(params).then((res)=>{
                            if(res.success){
                                this.visible = false;
                                this.$message.success('操作成功,请等待生成账单!')
                                if( this.regionId && this.cityId && this.organizeId ){
                                    this.getBillList()
                                }
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    } else {
                        this.validStatus = false
                        return false;
                    }
                });
            },
            
            cancelForm() {
                this.visible = false
            },
            // 附件下载
            exportHand(record) {
                this.$message.loading({ content: '附件下载中，请稍候！', key });
                let url = record.fileUrl
                let name = record.fileName
                downFile(url).then((data)=>{
                    if (!data) {
                        this.$message.warning("文件下载失败")
                        return
                    }
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), name)

                        this.$message.success({ content: '附件下载完成!', key, duration: 3 });
                    }else{
                        let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
                        let link = document.createElement('a')
                        link.style.display = 'none'
                        link.href = url
                        link.setAttribute('download', name)
                        document.body.appendChild(link)
                        link.click()
                        document.body.removeChild(link); //下载完成移除元素
                        window.URL.revokeObjectURL(url); //释放掉blob对象

                        this.$message.success({ content: '附件下载完成!', key, duration: 3 });
                    }
                })
            },
            // 获取当前页数、条数
            pageChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getBillList()
            },
            // 获取当前页数、条数
            sizeChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getBillList()
            },

            // 表单客户
            formCustomerChange(value) {
                this.form.customerCode = value
                this.form.ownerCode = undefined
                if(this.form.customerCode){
                    let params = {
                        whCode: this.form.code,
                        customerCode: this.form.customerCode,
                    }
                    getOwnerName(params).then((res)=>{
                        if(res.success){
                            this.form.ownerList = res.result
                        }else{
                            this.$message.warning(res.message, 6)
                        }
                    })
                }
            },
            // 表单货主
            formOwnerChange() {

            },
            clearChange() {
                this.disabledCurrent = null
            },
            onCalendarChange (obtain) {
            // 获取手动选择的时间段起始值
                this.disabledCurrent = obtain[0]
            },
            //  时间限制范围 开始时间~结束时间不能超过一个月，且禁选超过当前日期时间
            disabledDate (current) {
            if (!this.disabledCurrent) return current > moment()
                return (current && current < moment(this.disabledCurrent).subtract(1, 'M').startOf('day')) || current > moment(this.disabledCurrent).add(1, 'M').endOf('day') || current > moment()
            },
            openChange() {
                this.disabledCurrent = null
            },
        },
        computed: {
            getStartDate() {
                let resultDate, year, month, date
                let currDate = new Date()
                year = currDate.getFullYear()
                month = currDate.getMonth() + 1
                date = currDate.getDate()
                switch (month) {
                    case 1:
                    month += 11
                    year--
                    break
                    default:
                    month -= 1
                    break
                }
                month = (month < 10) ? ('0' + month) : month
                date = (date < 10) ? ('0' + date) : date
                resultDate = `${year}-${month}-${date} 00:00:00`
                return resultDate
            },
            getEndDate() {
                let resultDate, year, month, date
                let currDate = new Date()
                year = currDate.getFullYear()
                month = currDate.getMonth() + 1
                date = currDate.getDate()
                month = (month < 10) ? ('0' + month) : month
                date = (date < 10) ? ('0' + date) : date
                resultDate = `${year}-${month}-${date} 00:00:00`
                return resultDate
                }
            },
    }
</script>

<style lang="less" scoped>
    .settlementBill{
        width: 100%;
        padding: 0 10px 10px 10px;
        font-style: Microsoft YaHei;
        background: #ffffff;
        box-sizing: border-box;
        .top_operation{
            margin-bottom: 10px;
            overflow: hidden;
            .every_operation{
                float: left;
                margin-top: 10px;
                margin-right: 20px;
                span{
                    display: inline-block;
                    width: 85px;
                }
            }
            .button_div{
                float: left;
                margin-top: 10px;
            }
        }
        .table_div{
            .table_div_main{
                margin-top: 10px;
            }
        }
    }
</style>